import React from 'react';
import { Breadcrumb, Icon, Table, Button, Modal, Form, Input, Upload, message } from 'antd';
import './recommend.less';
import $ from 'jquery';
import Config from '../../common/config';
import Recommendproduct from './recommendproduct';

const config = new Config();
const FormItem = Form.Item;
const { TextArea } = Input;
const token = sessionStorage.getItem('token');

//楼层信息的表单
const RecommendForm = Form.create()(
    (props) => {
        const { form, normFile, beforeUpload, fileList, previewImg } = props;
        const { getFieldDecorator } = form;
        const formItemLayout = { labelCol: { span: 7 }, wrapperCol: { span: 17 }, };
        return (
            <Form layout="vertical">
                <FormItem {...formItemLayout} label="活动名称" hasFeedback style={{ minHeight: '70px', marginBottom: 0 }}>
                    {getFieldDecorator('recommendName', {
                        rules: [{ required: true, max: 10, message: '请输入活动名称，不超过10个字' }],
                    })(
                        <Input type="text" placeholder="请输入活动名称" />
                    )}
                </FormItem>
                <FormItem {...formItemLayout} label="主题图片" style={{ minHeight: '120px', marginBottom: 0 }}>
                    {getFieldDecorator('Filedata', {
                        valuePropName: 'fileList', getValueFromEvent: normFile,
                        rules: [{ required: true, message: '请上传主题图片' }],
                    })(
                        <Upload
                            accept="image/*"
                            name="Filedata"
                            action={config.UploadFile + "/uploadpageimg"}
                            beforeUpload={beforeUpload}
                            listType="picture-card"
                            className="upload-list-inline"
                            onPreview={previewImg}
                            style={{ float: 'left' }}
                        >
                            {
                                fileList.length >= 1 ? null :
                                    <div>
                                        <Icon type="plus" />
                                        <div className="ant-upload-text">点击上传图片</div>
                                    </div>
                            }
                        </Upload>
                    )}
                    <p style={{ float: 'left', width:'100%' }}>轮播图尺寸: 240*410</p>
                </FormItem>
            </Form>
        );
    }
);
export default class Recommend extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            fileList: [],
            previewVisible: false,
            previewImage: '',
            productvisible: false,
            products: new Array(4).fill(undefined),
        }
    }
    componentDidMount() {
        this.getRecommendList();
    }
    //加载推荐信息
    getRecommendList() {
        $.ajax({
            url: `${config.JuseHomepage}/recommend/detail`,
            type: "get",
            async: true,
            headers: {
                'Authorization': 'Bearer ' + token,
            },
            success: res => {
                console.log('推荐信息', res)
                if (res.code === 200) {
                    if (res.data) {
                        const { fileList } = this.state;
                        fileList.push({
                            uid: -1,
                            name: res.data.imgName,
                            status: 'done',
                            url: config.Filepath + res.data.imgName
                        });
                        console.log('fileList', fileList)
                        this.recommendForm.setFieldsValue({
                            recommendName: res.data.recommendName,
                            Filedata: fileList
                        });
                        this.setState({
                            products: res.data.productList,
                            fileList
                        })
                    } else {
                        this.recommendForm.setFieldsValue({
                            recommendName: "",
                            Filedata: []
                        });
                        this.setState({
                            products: new Array(4).fill(undefined),
                            fileList: []
                        })
                    }
                } else {
                    message.error('推荐商品信息加载失败，请返回重新操作', 2);
                }
            }
        });
    }
    //限制用户必须上传图片格式的文件、图片大小
    beforeUpload(file, fileList) {
        let isIMG = file.type.indexOf('image') != -1;
        if (!isIMG) {
            message.config({ top: 50 });
            message.error('您只能上传图片！');
        }
        let isLt10M = file.size / 1024 / 1024 < 10;
        if (!isLt10M) {
            message.config({ top: 50 });
            message.error('您上传的图片大小必须小于10MB！');
        }
        return isIMG && isLt10M;
    }
    //上传图片
    normFile(e) {
        this.setState({
            fileList: e.fileList
        });
        if (Array.isArray(e)) {
            return e;
        }
        return e && e.fileList;
    };
    //获取表单元素
    saveRecommendFormRef(form) {
        this.recommendForm = form;
    }
    //预览图片对话框
    previewImg(file) {
        this.setState({
            previewImage: file.url || file.thumbUrl,
            previewVisible: true,
        });
    }
    //关闭预览图片对话框
    cancelPreview() {
        this.setState({ previewVisible: false })
    }
    //保存
    saveRecommend() {
        this.recommendForm.validateFields((err, values) => {
            if (!err) {
                const { products } = this.state;
                let productIds = [];
                for (let val of products) {
                    if (val) {
                        productIds.push(val.productId)
                    }
                }
                if (productIds.length == 4) {
                    $.ajax({
                        url: `${config.JuseHomepage}/recommend/save`,
                        type: "post",
                        async: true,
                        headers: {
                            'Authorization': 'Bearer ' + token,
                        },
                        data: {
                            recommendName: values.recommendName,
                            imgName: values.Filedata[0].response ? values.Filedata[0].response.name : values.Filedata[0].name,
                            productIds: productIds
                        },
                        success: res => {
                            if (res.code === 200) {
                                message.success('保存推荐商品信息成功！', 2);
                            } else {
                                Modal.warning({
                                    title: '保存失败',
                                    content: `请返回重新操作`,
                                });
                            }
                        }
                    });
                } else {
                    Modal.warning({
                        title: '保存失败',
                        content: `楼层必须包含4个展示商品！`,
                    });
                }
            } else {
                Modal.warning({
                    title: '保存失败',
                    content: `请填写必要的信息，再提交`,
                });
            }
        })
    }
    //添加商品的对话框组件
    addProductModal() {
        const { products } = this.state;
        let flag = true;
        for (let value of products) {
            if (!value) {
                flag = false;
                break;
            }
        }
        if (flag) {
            message.error('添加商品数已达到上限4个，请先删除再添加', 2);
        } else {
            this.setState({
                productvisible: true,
            })
        }
    }
    //确认添加商品
    addProduct(products) {
        this.setState({
            productvisible: false,
            products
        })
    }
    //取消添加商品
    cancelProduct() {
        this.setState({
            productvisible: false
        })
    }
    //移动商品
    moveProduct(index, toindex) {
        const { products } = this.state;
        const item = products[index];
        products[index] = products[toindex];
        products[toindex] = item;
        this.setState({
            products
        })
    }
    //删除商品
    deleteProduct(index) {
        const { products } = this.state;
        products[index] = undefined;
        this.setState({
            products
        })
    }
    render() {
        return (
            <div className='goods-label'>
                <div className='goods-label-cont clearfix'>
                    <div className='goods-label-cont-nav clearfix'>
                        <Breadcrumb separator=">">
                            <Breadcrumb.Item>首页管理</Breadcrumb.Item>
                            <Breadcrumb.Item>推荐管理</Breadcrumb.Item>
                        </Breadcrumb>
                    </div>
                    <Button onClick={this.saveRecommend.bind(this)} className="floor-savebtn">保存</Button>
                    <div className='allgoods-table clearfix' >
                        <div className="floor-msg recommend-msg">
                            {/* 楼层信息表单 */}
                            <RecommendForm
                                ref={this.saveRecommendFormRef.bind(this)}
                                normFile={this.normFile.bind(this)}
                                beforeUpload={this.beforeUpload.bind(this)}
                                fileList={this.state.fileList}
                                previewImg={this.previewImg.bind(this)}
                            />
                            {/* 预览图片对话框 */}
                            <Modal visible={this.state.previewVisible} footer={null} onCancel={this.cancelPreview.bind(this)} style={{ top: "20%" }}>
                                <img alt="example" style={{ width: '100%' }} src={this.state.previewImage} />
                            </Modal>
                        </div>
                        <div className="recommend-products">
                            <p style={{ fontSize: "16px", marginBottom: "5px", marginLeft: "1%" }}>添加商品<Button className='floor-addbtn' width={160} icon="plus" onClick={this.addProductModal.bind(this)}></Button></p>
                            <ul>
                                {
                                    this.state.products.map((item, index) => {
                                        if (item) {
                                            return (<li key={index}>
                                                <img src={item.imageUrl + item.listImage} className="floor-pimg" />
                                                <p className="recommend-name-p">{item.productName}</p>
                                                <div className="floor-pmove">
                                                    {index > 0 && <a onClick={this.moveProduct.bind(this, index, index - 1)} style={{ marginRight: "6%" }}><Icon type="arrow-up" />上移</a>}
                                                    {index < 3 && <a onClick={this.moveProduct.bind(this, index, index + 1)} style={{ marginRight: "6%" }}><Icon type="arrow-down" />下移</a>}
                                                    <a onClick={this.deleteProduct.bind(this, index)}><Icon type="close" />删除</a>
                                                </div>
                                            </li>)
                                        } else {
                                            return (<li key={index}>
                                                <p style={{ lineHeight: "200px" }}>{"请添加商品"}</p>
                                            </li>)
                                        }
                                    })
                                }
                            </ul>
                            <Recommendproduct
                                visible={this.state.productvisible}
                                products={this.state.products}
                                addProduct={this.addProduct.bind(this)}
                                cancelProduct={this.cancelProduct.bind(this)}
                            />
                        </div>
                    </div>
                </div>
            </div>
        )
    }
}